// 登录和注册功能
document.addEventListener('DOMContentLoaded', () => {
    const loginLink = document.getElementById('login-link');
    const registerLink = document.getElementById('register-link');
    const logoutLink = document.getElementById('logout-link');
    const loginForm = document.getElementById('login-form');
    const registerForm = document.getElementById('register-form');
    const app = document.getElementById('app');
  
    // 显示登录表单
    loginLink.addEventListener('click', (e) => {
      e.preventDefault();
      loginForm.style.display = 'block';
      registerForm.style.display = 'none';
      app.style.display = 'none';
    });
  
    // 显示注册表单
    registerLink.addEventListener('click', (e) => {
      e.preventDefault();
      registerForm.style.display = 'block';
      loginForm.style.display = 'none';
      app.style.display = 'none';
    });
  
    // 登录表单提交
    document.getElementById('login').addEventListener('submit', async (e) => {
      e.preventDefault();
      const email = document.getElementById('login-email').value;
      const password = document.getElementById('login-password').value;
  
      try {
        const response = await fetch('/api/auth/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ email, password }),
        });
        const data = await response.json();
        if (response.ok) {
          localStorage.setItem('token', data.token);
          localStorage.setItem('user', JSON.stringify(data.user));
          loginForm.style.display = 'none';
          registerForm.style.display = 'none';
          app.style.display = 'block';
          loginLink.style.display = 'none';
          registerLink.style.display = 'none';
          logoutLink.style.display = 'block';
          // 加载用户数据
          loadUserProfile();
          loadPosts();
          loadFriends();
        } else {
          alert(data.error);
        }
      } catch (error) {
        console.error('Login error:', error);
        alert('Login failed. Please try again.');
      }
    });
  
    // 注册表单提交
    document.getElementById('register').addEventListener('submit', async (e) => {
      e.preventDefault();
      const email = document.getElementById('register-email').value;
      const password = document.getElementById('register-password').value;
      const name = document.getElementById('register-name').value;
  
      try {
        const response = await fetch('/api/auth/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ email, password, profile: { name } }),
        });
        const data = await response.json();
        if (response.ok) {
          alert('Registration successful! Please login.');
          loginForm.style.display = 'block';
          registerForm.style.display = 'none';
        } else {
          alert(data.error);
        }
      } catch (error) {
        console.error('Registration error:', error);
        alert('Registration failed. Please try again.');
      }
    });
  
    // 退出登录
    logoutLink.addEventListener('click', (e) => {
      e.preventDefault();
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      app.style.display = 'none';
      loginForm.style.display = 'none';
      registerForm.style.display = 'block';
      loginLink.style.display = 'block';
      registerLink.style.display = 'block';
      logoutLink.style.display = 'none';
    });
  
    // 加载用户资料
    const loadUserProfile = async () => {
      const token = localStorage.getItem('token');
      try {
        const response = await fetch('/api/auth/me', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });
        const data = await response.json();
        if (response.ok) {
          const profileInfo = document.getElementById('profile-info');
          profileInfo.innerHTML = `
            <h3>${data.profile.name}</h3>
            <p>Email: ${data.email}</p>
            <p>Bio: ${data.profile.bio || 'No bio provided'}</p>
          `;
        }
      } catch (error) {
        console.error('Failed to load user profile:', error);
      }
    };
  });